// WebSocket配置
const wsConfig = {
  // WebSocket服务器地址
  baseUrl: 'ws://localhost:9222',
  
  // 重连配置
  reconnect: {
    // 是否自动重连
    auto: true,
    // 重连间隔(ms)
    delay: 5000,
    // 最大重连次数
    maxAttempts: 10
  },

  // 心跳配置
  heartbeat: {
    // 心跳间隔(ms)
    interval: 1000,
    // 心跳超时时间(ms)
    timeout: 3000,
    // 心跳消息
    message: 'ping'
  }
}

class WebSocketClient {
  constructor(path, options = {}) {
    this.path = path
    this.options = { ...wsConfig, ...options }
    this.ws = null
    this.lockReconnect = false
    this.reconnectAttempts = 0
    this.heartbeatTimer = null
    this.serverTimer = null
  }

  connect() {
    try {
      const url = this.options.baseUrl + this.path
      console.log('正在连接WebSocket:', url)
      this.ws = new WebSocket(url)
      this.initEventHandlers()
    } catch (e) {
      console.error('WebSocket连接失败:', e)
      this.reconnect()
    }
  }

  initEventHandlers() {
    this.ws.onopen = () => {
      console.log('WebSocket连接成功')
      this.reconnectAttempts = 0
      this.startHeartbeat()
      if (this.options.onOpen) {
        this.options.onOpen()
      }
    }

    this.ws.onclose = (event) => {
      console.log('WebSocket连接关闭:', event.code, event.reason)
      this.stopHeartbeat()
      if (this.options.onClose) {
        this.options.onClose(event)
      }
      this.reconnect()
    }

    this.ws.onerror = (error) => {
      console.error('WebSocket错误:', error)
      if (this.options.onError) {
        this.options.onError(error)
      }
    }

    this.ws.onmessage = (event) => {
      if (event.data === 'pong') {
        this.resetHeartbeat()
      } else if (this.options.onMessage) {
        this.options.onMessage(event)
      }
    }
  }

  send(data) {
    if (this.ws && this.ws.readyState === WebSocket.OPEN) {
      this.ws.send(data)
    }
  }

  reconnect() {
    if (this.lockReconnect || 
        this.reconnectAttempts >= this.options.reconnect.maxAttempts) return
        
    this.lockReconnect = true
    console.log(`尝试第${this.reconnectAttempts + 1}次重连...`)
    
    setTimeout(() => {
      this.connect()
      this.lockReconnect = false
      this.reconnectAttempts++
    }, this.options.reconnect.delay)
  }

  startHeartbeat() {
    this.heartbeatTimer = setInterval(() => {
      this.send(this.options.heartbeat.message)
      this.serverTimer = setTimeout(() => {
        this.ws.close()
      }, this.options.heartbeat.timeout)
    }, this.options.heartbeat.interval)
  }

  resetHeartbeat() {
    clearTimeout(this.serverTimer)
  }

  stopHeartbeat() {
    clearInterval(this.heartbeatTimer)
    clearTimeout(this.serverTimer)
  }

  close() {
    this.stopHeartbeat()
    if (this.ws) {
      this.ws.close()
    }
  }
}

export default WebSocketClient 